#!/bin/bash

# 启动RuoYi-TDesign后台服务的脚本
# 包括MySQL、Redis等依赖服务

# 添加自动克隆和初始化功能
echo "=== 克隆和初始化项目 ==="
# 删除现有的micro-tdesign-vue目录（如果存在）
if [ -d "micro-tdesign-vue" ]; then
    echo "删除现有的micro-tdesign-vue目录..."
    rm -rf micro-tdesign-vue
    if [ $? -eq 0 ]; then
        echo "成功删除现有的micro-tdesign-vue目录"
    else
        echo "删除现有的micro-tdesign-vue目录失败"
        exit 1
    fi
fi

# 克隆项目
echo "克隆项目..."
git clone https://gitee.com/blogfz.com/micro-tdesign-vue.git
if [ $? -eq 0 ]; then
    echo "项目克隆成功"
    # 进入项目目录并设置执行权限
    cd micro-tdesign-vue
    if [ -f "start-backend-services.sh" ]; then
        chmod +x start-backend-services.sh
        echo "已设置脚本执行权限"
    else
        echo "警告: 未找到 start-backend-services.sh 脚本"
    fi
    cd ..
else
    echo "项目克隆失败"
    exit 1
fi

echo "开始启动后台服务..."

# 检查Docker是否已安装
if ! command -v docker &> /dev/null; then
    echo "错误: 未检测到 Docker，请先安装 Docker"
    exit 1
fi

# 检查Docker Compose是否已安装
if ! command -v docker-compose &> /dev/null; then
    echo "错误: 未检测到 Docker Compose，请先安装 Docker Compose"
    exit 1
fi

# 检查端口是否被占用
echo "检查端口占用情况..."
# 检查lsof命令是否存在
if command -v lsof &> /dev/null; then
    if lsof -Pi :3306 -sTCP:LISTEN -t >/dev/null ; then
        echo "警告: 3306端口已被占用"
    fi

    if lsof -Pi :6379 -sTCP:LISTEN -t >/dev/null ; then
        echo "警告: 6379端口已被占用"
    fi

    if lsof -Pi :9000 -sTCP:LISTEN -t >/dev/null ; then
        echo "警告: 9000端口已被占用"
    fi

    if lsof -Pi :9001 -sTCP:LISTEN -t >/dev/null ; then
        echo "警告: 9001端口已被占用"
    fi
else
    echo "提示: lsof命令未安装，跳过端口占用检查"
fi

# 创建必要的目录和配置文件
echo "创建必要的目录和配置文件..."

# 创建MySQL相关目录
mkdir -p ./script/docker/mysql/data
mkdir -p ./script/docker/mysql/conf

# 创建Redis相关目录
mkdir -p ./script/docker/redis/data
mkdir -p ./script/docker/redis/conf

# 创建MinIO相关目录
mkdir -p ./script/docker/minio/data

# 创建后端服务日志目录
mkdir -p ./logs

# 复制默认配置文件（如果不存在）
if [ ! -f ./script/docker/mysql/conf/my.cnf ]; then
    echo "创建默认MySQL配置文件..."
    cat > ./script/docker/mysql/conf/my.cnf << 'EOF'
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
default-time-zone = '+8:00'
lower_case_table_names = 1
max_connections = 2000
sql_mode = NO_ENGINE_SUBSTITUTION
# 稳定的InnoDB配置
innodb_flush_method = O_DSYNC
innodb_use_native_aio = 0
innodb_flush_log_at_trx_commit = 1
innodb_file_per_table = 1

[mysql]
default-character-set = utf8mb4

[client]
default-character-set = utf8mb4
EOF
fi

if [ ! -f ./script/docker/redis/conf/redis.conf ]; then
    echo "创建默认Redis配置文件..."
    cat > ./script/docker/redis/conf/redis.conf << 'EOF'
# Redis配置文件
bind 0.0.0.0
port 6379
timeout 0
tcp-keepalive 0
loglevel notice
logfile ""
databases 16
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /data
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-disable-tcp-nodelay no
slave-priority 100
maxmemory 268435456
maxmemory-policy allkeys-lru
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
cluster-node-timeout 15000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes
requirepass gzkj666
EOF
fi

# 创建后端服务的docker-compose文件
echo "创建后端服务docker-compose文件..."
cat > ./docker-compose-backend.yml << 'EOF'
services:
  mysql:
    image: mysql:8.0.33
    container_name: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: gzkj666
      MYSQL_DATABASE: ruoyi-tdesign
      TZ: Asia/Shanghai
    ports:
      - "3306:3306"
    volumes:
      - ./script/docker/mysql/data:/var/lib/mysql
      - ./script/docker/mysql/conf:/etc/mysql/conf.d
    command:
      - "--default-authentication-plugin=mysql_native_password"
      - "--character-set-server=utf8mb4"
      - "--collation-server=utf8mb4_general_ci"
      - "--explicit_defaults_for_timestamp=true"
      - "--lower_case_table_names=1"
      - "--innodb-flush-method=O_DSYNC"
      - "--innodb-use-native-aio=0"
      - "--innodb-flush-log-at-trx-commit=1"
    networks:
      - ruoyi-network
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      timeout: 20s
      retries: 10
    user: "999:999"

  redis:
    image: redis:7-alpine
    container_name: redis
    restart: always
    ports:
      - "6379:6379"
    environment:
      TZ: Asia/Shanghai
    volumes:
      - ./script/docker/redis/data:/data
      - ./script/docker/redis/conf/redis.conf:/usr/local/etc/redis/redis.conf
    command: redis-server /usr/local/etc/redis/redis.conf
    networks:
      - ruoyi-network

  minio:
    image: minio/minio:RELEASE.2023-04-13T03-08-07Z
    container_name: minio
    restart: always
    ports:
      - "9000:9000"
      - "9001:9001"
    environment:
      MINIO_ROOT_USER: ruoyi
      MINIO_ROOT_PASSWORD: ruoyi123
      TZ: Asia/Shanghai
    volumes:
      - ./script/docker/minio/data:/data
    command: server --address ':9000' --console-address ':9001' /data
    networks:
      - ruoyi-network

networks:
  ruoyi-network:
    driver: bridge
EOF

# 停止并移除现有的容器
echo "停止并移除现有的容器..."
# 检查docker-compose文件是否存在且有效
if [ -f "./docker-compose-backend.yml" ]; then
    # 验证YAML语法
    if docker-compose -f docker-compose-backend.yml config > /dev/null 2>&1; then
        docker-compose -f docker-compose-backend.yml down
    else
        echo "警告: docker-compose文件存在语法错误，跳过停止容器步骤"
    fi
else
    echo "提示: docker-compose文件不存在，跳过停止容器步骤"
fi

# 清理数据目录并设置正确权限
echo "清理数据目录并设置权限..."
# 检查MySQL是否已经在运行
if docker ps | grep -q mysql; then
    echo "MySQL已经在运行，跳过数据目录清理"
else
    echo "MySQL未运行，进行数据目录清理"
    # 更彻底地清理MySQL数据目录
    if [ -d "./script/docker/mysql/data" ]; then
        # 停止可能正在运行的MySQL容器
        docker stop mysql 2>/dev/null || true
        # 删除所有文件
        rm -rf ./script/docker/mysql/data/*
        # 确保目录存在且为空
        mkdir -p ./script/docker/mysql/data
        # 验证目录是否为空
        if [ "$(ls -A ./script/docker/mysql/data)" ]; then
            echo "警告: MySQL数据目录可能未完全清理"
        else
            echo "MySQL数据目录已清空"
        fi
        # 等待一下确保文件系统同步
        sleep 2
    fi
fi

# 清理Redis数据目录
if [ -d "./script/docker/redis/data" ]; then
    # 停止可能正在运行的Redis容器
    docker stop redis 2>/dev/null || true
    rm -rf ./script/docker/redis/data/*
    mkdir -p ./script/docker/redis/data
    # 验证目录是否为空
    if [ "$(ls -A ./script/docker/redis/data)" ]; then
        echo "警告: Redis数据目录可能未完全清理"
    else
        echo "Redis数据目录已清空"
    fi
    sleep 2
fi

# 清理MinIO数据目录
if [ -d "./script/docker/minio/data" ]; then
    # 停止可能正在运行的MinIO容器
    docker stop minio 2>/dev/null || true
    rm -rf ./script/docker/minio/data/*
    mkdir -p ./script/docker/minio/data
    # 验证目录是否为空
    if [ "$(ls -A ./script/docker/minio/data)" ]; then
        echo "警告: MinIO数据目录可能未完全清理"
    else
        echo "MinIO数据目录已清空"
    fi
    sleep 2
fi

# 设置正确的权限 (使用更安全的方式)
echo "设置MySQL数据目录权限..."
mkdir -p ./script/docker/mysql/data
chown -R 999:999 ./script/docker/mysql/data
chmod -R 755 ./script/docker/mysql/data

echo "设置Redis数据目录权限..."
mkdir -p ./script/docker/redis/data
chmod -R 755 ./script/docker/redis/data

echo "设置MinIO数据目录权限..."
mkdir -p ./script/docker/minio/data
chmod -R 755 ./script/docker/minio/data

# 启动后台服务
echo "启动后台服务..."
if [ -f "./docker-compose-backend.yml" ]; then
    # 验证YAML语法
    if docker-compose -f docker-compose-backend.yml config > /dev/null 2>&1; then
        docker-compose -f docker-compose-backend.yml up -d
    else
        echo "错误: docker-compose文件存在语法错误，无法启动服务"
        echo "请检查docker-compose-backend.yml文件的YAML语法"
        exit 1
    fi
else
    echo "错误: docker-compose文件不存在，无法启动服务"
    exit 1
fi

# 等待服务启动
echo "等待服务启动..."
sleep 10

# 检查服务状态
echo "检查服务状态..."
docker-compose -f docker-compose-backend.yml ps

# 逐个检查服务并显示详细日志
echo "=== 检查MySQL状态 ==="
if docker ps | grep -q mysql; then
    echo "MySQL正在运行"
    echo "MySQL最近日志:"
    docker logs mysql 2>&1 | tail -20
else
    echo "MySQL未运行，尝试查看错误日志:"
    docker logs mysql 2>&1 || echo "无法获取MySQL日志"
fi

echo "=== 检查Redis状态 ==="
if docker ps | grep -q redis; then
    echo "Redis正在运行"
    echo "Redis最近日志:"
    docker logs redis 2>&1 | tail -20
else
    echo "Redis未运行，尝试查看错误日志:"
    docker logs redis 2>&1 || echo "无法获取Redis日志"
fi

echo "=== 检查MinIO状态 ==="
if docker ps | grep -q minio; then
    echo "MinIO正在运行"
    echo "MinIO最近日志:"
    docker logs minio 2>&1 | tail -20
else
    echo "MinIO未运行，尝试查看错误日志:"
    docker logs minio 2>&1 || echo "无法获取MinIO日志"
fi

# 再等待一段时间让服务完全启动
echo "再等待20秒让服务完全启动..."
sleep 20

# 最终状态检查
echo "=== 最终服务状态 ==="
docker-compose -f docker-compose-backend.yml ps

echo "后台服务启动完成！"
echo "MySQL: localhost:3306 (root/gzkj666)"
echo "Redis: localhost:6379 (password: gzkj666)"
echo "MinIO: http://localhost:9000 (ruoyi/ruoyi123)"